package com.yikaiye.android.yikaiye.utils;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.inputmethod.InputMethodManager;

import androidx.core.content.FileProvider;

import com.yikaiye.android.yikaiye.application.MyApplication;
import com.yikaiye.android.yikaiye.config.Constant;
import com.yikaiye.android.yikaiye.ui.activity.MainActivity;
import com.yikaiye.android.yikaiye.ui.activity.login.LoginActivity;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.File;

public class CommonUtil {
    // 两次点击按钮之间的点击间隔不能少于800毫秒
    private static final int MIN_CLICK_DELAY_TIME = 800;
    private static long lastClickTime;

    public static boolean isCanClick() {
        boolean flag = false;
        long curClickTime = System.currentTimeMillis();
        if ((curClickTime - lastClickTime) >= MIN_CLICK_DELAY_TIME) {
            flag = true;
        }
        lastClickTime = curClickTime;
        return flag;
    }

    /**
     * 隐藏软键盘
     */
    public static void closeKeyboard(Activity activity) {
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm.isActive() && activity.getCurrentFocus() != null) {
            if (activity.getCurrentFocus().getWindowToken() != null) {
                imm.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }

    /**
     * 检查是否登录
     */
    public static boolean isLogin(Context context) {
        if (!MyApplication.manager.isLogin()) {
            Intent intent = new Intent(context, LoginActivity.class);
            context.startActivity(intent);
            return false;
        }
        return true;
    }

    public static void jumpToLogin(Activity activity) {
        MyApplication.manager.clearUserInfo();
        MyApplication.getInstance().popAllActivityExceptOne();
        MyApplication.getInstance().exit();
        JumpIntent.jump(activity, LoginActivity.class);
    }

    public static void jumpToMain(Activity activity) {
        MyApplication.getInstance().popAllActivityExceptOne();
//        MyApplication.getInstance().exit();
        JumpIntent.jump(activity, MainActivity.class);
    }

    /**
     * 将html文本内容中包含img标签的图片，宽度变为屏幕宽度，高度根据宽度比例自适应
     */
    public static String getNewContent(String htmlText) {
        try {
            Document doc = Jsoup.parse(htmlText);
            Elements elements = doc.getElementsByTag("img");
            for (Element element : elements) {
                element.attr("width", "100%").attr("height", "auto");
            }
            return doc.toString();
        } catch (Exception e) {
            return htmlText;
        }
    }

    /**
     * 裁剪图片方法实现
     */
    public static void setIntent(Intent intent, Uri uri, Uri imageUri) {
        intent.setDataAndType(uri, "image/*");
        // crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        // 去黑边
        intent.putExtra("scale", true);
        intent.putExtra("scaleUpIfNeeded", true);
        // aspectX aspectY 是宽高的比例，根据自己情况修改
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高像素
        intent.putExtra("outputX", 400);
        intent.putExtra("outputY", 400);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        //取消人脸识别功能
        intent.putExtra("noFaceDetection", true);
        //设置返回的uri
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        //设置为不返回数据
        intent.putExtra("return-data", false);
    }

    public static String checkText(String s) {
        if (TextUtils.isEmpty(s)) {
            return "";
        }
        return s;
    }

    public static void installAPK(Context context, String apkPath) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        //版本在7.0以上是不能直接通过uri访问的
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            File file = (new File(apkPath));
            // 由于没有在Activity环境下启动Activity,设置下面的标签
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            //参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致   参数3  共享的文件
            Uri apkUri = FileProvider.getUriForFile(context, Constant.APP_PROVIDER, file);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(new File(apkPath)), "application/vnd.android.package-archive");
        }
        context.startActivity(intent);
    }

    /**
     * 获取文件path
     *
     * @param context 上下文
     * @param uri     uri
     * @return path
     */
    public static String getRealFilePath(final Context context, final Uri uri) {
        if (null == uri) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }

    /**
     * 6-18位数字和字母组成的密码
     */
    public static boolean checkPassword(String password) {
        String regex = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,18}$";
        return password.matches(regex);
    }

    /**
     * 小数点0去掉
     */
    public static String getResultForDouble(double number) {
        String numberString = String.valueOf(number);
        if (numberString.contains(".")) {
            if (numberString.endsWith(".0")) {
                return numberString.substring(0, numberString.length() - 2);
            }
            int endIndex = numberString.length() - 1;
            for (int i = endIndex; i >= 0; i--) {
                char c = numberString.charAt(i);
                if (c != '0') {
                    endIndex = i;
                    break;
                }
            }
            return numberString.substring(0, endIndex + 1);
        } else {
            return numberString;
        }
    }

    public static String setText(String s) {
        if (TextUtils.isEmpty(s)) {
            return "—";
        }
        return s;
    }

    /**
     * 获取脱敏手机号  后四位****
     */
    public static String getEncryptPhone(String phoneNumber) {
        if (!TextUtils.isEmpty(phoneNumber) && phoneNumber.length() == 11) {
            return phoneNumber.substring(0, 7) + "****";
        }
        return phoneNumber;
    }

    /**
     * 2024-10-10 14:12:44---->20241010
     */
    public static String setTime(String time) {
        if (!TextUtils.isEmpty(time) && time.length() >= 10) {
            return time.substring(0, 10).replaceAll("-", "");
        }
        return time;
    }
}
